package com.sun.evening.manager.service.impl;

import com.sun.evening.dao.dto.PictureInsertDto;
import com.sun.evening.dao.mapper.PictureListMapper;
import com.sun.evening.manager.minio.MinioUtils;
import com.sun.evening.manager.service.RootService;
import io.minio.Result;
import io.minio.messages.Item;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
@Service
public class RootServiceImpl implements RootService {
    @Resource
    private PictureListMapper pictureListMapper;
    @Resource
    private MinioUtils minioUtils;
    @Override
    @Transactional(rollbackFor = {Exception.class} )
    @ApiModelProperty("管理员插入图片集并返回结果")
    public List<PictureInsertDto> insertImages (List<MultipartFile> imageList, String path) throws Exception {
        //以流的形式做处理并上传
        for (MultipartFile image : imageList) {
            InputStream inputStream = image.getInputStream();
            String url = path + "/" + image.getOriginalFilename();
            minioUtils.uploadFile("picture", url, inputStream);
        }
        //存储到minio之后进行数据库图片数据插入并返回插入对象
        Iterable<Result<Item>> pictureNameList=minioUtils.listObjects("picture",path,true);
        int count = 0;
        List<PictureInsertDto> pictureInsertDtoList=new ArrayList<>();
        for (Result<Item> result : pictureNameList) {
            count++;
            PictureInsertDto pictureInsertDto=new PictureInsertDto();
            Item item = result.get();
            pictureInsertDto.setPictureName(item.objectName());
            pictureInsertDto.setPictureId(path+"M"+count);
            pictureInsertDto.setPictureNumber(path);
            pictureInsertDtoList.add(pictureInsertDto);
        }
        int rows=pictureListMapper.insertPictureListDto(pictureInsertDtoList);
        if (rows!=pictureInsertDtoList.size()){
            return null;
        }
        return pictureInsertDtoList;
    }
}
